﻿
using JinYuan.Helper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;

namespace JinYuan.DAL
{
    public class SQLSugarHelper
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static string connString = string.Empty;

        /// <summary>
        /// 数据库类型
        /// </summary>
        public static SqlSugar.DbType dbType = SqlSugar.DbType.SqlServer;

        public static SqlSugarScope SqlSugarClient
        {
            get
            {
                //如果配置了 SlaveConnectionConfigs那就是主从模式,所有的写入删除更新都走主库，查询走从库，
                var db = new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = connString,
                    DbType = dbType, //数据库类型
                    IsAutoCloseConnection = true, //默认false,自动释放和关闭数据库连接，设置为true无需使用using或者close操作
                    InitKeyType = InitKeyType.Attribute //默认SystemTable,该属性是不是主键，是不是标识列等等信息

                });
                db.Ado.CommandTimeOut = 3000;//设置执行语法超时时间
                db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
                {
                    LogHelper.Instance.WriteLog($"执行时间：{db.Ado.SqlExecutionTime.TotalMilliseconds}毫秒 \r\nSQL如下：{sql} \r\n参数：{GetParams(pars)} ", "SQL执行");
                };
                db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
                {
                    if (db.TempItems == null) db.TempItems = new Dictionary<string, object>();
                };
                db.Aop.OnError = (exp) =>//执行SQL 错误事件
                {
                    LogHelper.Instance.WriteError($"SQL错误:{exp.Message}\r\nSQL如下：{exp.Sql}", "SQL执行");
                    throw new Exception(exp.Message);
                };
                db.Aop.OnDiffLogEvent = (it) => //可以方便拿到 数据库操作前和操作后的数据变化。
                {
                    var editBeforeData = it.BeforeData; //变化前数据
                    var editAfterData = it.AfterData; //变化后数据
                    var sql = it.Sql; //SQL
                    var parameter = it.Parameters; //参数
                    var data = it.BusinessData; //业务数据
                    var time = it.Time ?? new TimeSpan(); //时间
                    var diffType = it.DiffType; //枚举值 insert 、update 和 delete 用来作业务区分

                    //你可以在这里面写日志方法
                    var log = $"时间:{time.TotalMilliseconds}\r\n";
                    log += $"类型:{diffType.ToString()}\r\n";
                    log += $"SQL:{sql}\r\n";
                    log += $"参数:{GetParams(parameter)}\r\n";
                    log += $"业务数据:{JsonHelper.EntityToJson(data)}\r\n";
                    log += $"变化前数据:{JsonHelper.EntityToJson(editBeforeData)}\r\n";
                    log += $"变化后数据:{JsonHelper.EntityToJson(editAfterData)}\r\n";
                    //SqlLogHelper.WriteLog(log, "数据变化前后");
                };
                return db;
            }
        }

        /// <summary>
        /// 获取参数信息
        /// </summary>
        /// <param name="pars"></param>
        /// <returns></returns>
        private static string GetParams(SugarParameter[] pars)
        {
            return pars.Aggregate("", (current, p) => current + $"{p.ParameterName}:{p.Value}, ");
        }
    }
}
